package com.tz.crm.service.impl;


import com.tz.crm.dao.*;
import com.tz.crm.entity.Contact;
import com.tz.crm.entity.Customer;
import com.tz.crm.entity.Role;
import com.tz.crm.entity.User;
import com.tz.crm.entity.enumeration.Level;
import com.tz.crm.entity.enumeration.Source;
import com.tz.crm.entity.enumeration.Status;
import com.tz.crm.service.CustomerService;
import com.tz.crm.utils.Pager;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 客户的增删改查服务类
 */
@Service
@Transactional
@SuppressWarnings("unchecked")
public class CustomerServiceImpl extends BaseServiceImpl<Customer, String> implements CustomerService {

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private ContactDao contactDao;
    @Autowired
    private UserDao userDao;

    @Autowired
    private VisitRecordDao visitRecordDao;
    @Autowired
    private VisitTypeDao visitTypeDao;

    private static final Logger LOGGER = Logger.getLogger(CustomerServiceImpl.class);

    /**
     * 有参构造
     *
     * @param customerDao 注入的组件
     */
    @Autowired
    public CustomerServiceImpl(CustomerDao customerDao) {
        this.customerDao = customerDao;
        super.setBaseDao(customerDao);
    }

    @Override
         public Pager<Customer> getByPager(Customer customer, Pager pager) {
        DetachedCriteria detachedCriteria = DetachedCriteria
                .forClass(Customer.class);
        if (StringUtils.isNotBlank(customer.getName())) {
            detachedCriteria.add(Restrictions.like("name", customer.getName(),
                    MatchMode.ANYWHERE));
        }
        if (StringUtils.isNotBlank(customer.getAddress())) {
            detachedCriteria.add(Restrictions.like("address",
                    customer.getAddress()));
        }
        if (customer.getSource() != null) {
            detachedCriteria
                    .add(Restrictions.eq("source", customer.getSource()));
        }
         //判断是否是公海客户
        if (customer.getLevel() != null) {
            detachedCriteria.add(Restrictions.eq("level", customer.getLevel()));
        }
        detachedCriteria.add(Restrictions.isNotNull("backSeaUserId"));
        pager = visitRecordDao.findByPager(pager, detachedCriteria);
        return pager;
    }


    @Override
    public void saveLinkedContact(Customer customer) {
        // 设置初始状态: 未签约客户
        customerDao.save(customer);
        // 设置初始状态: 是主联系人
        Contact majorContact = customer.getMajorContact();
        majorContact.setMajor(true);
        majorContact.setCustomer(customer);
        contactDao.save(majorContact);
    }

    @Override
    public List<Customer> getAllSea() {
        return customerDao.getAllSea();
    }

    @Override
    public Pager<Customer> search(Customer customer, Pager pager, List<User> ownerList,
                                  List<Source> sourceList, List<Level> levelList, User user) {

        DetachedCriteria detachedCriteria = DetachedCriteria
                .forClass(Customer.class);
        /*
         * int number=customerDao.getCountNumber(customer); if(number==1){
		 * detachedCriteria.add(Restrictions.gt("firstVisit", true)); }
		 */
        if (StringUtils.isNotBlank(customer.getName())) {
            detachedCriteria.add(Restrictions.like("name", customer.getName(),
                    MatchMode.ANYWHERE));
        }
        if (StringUtils.isNotBlank(customer.getAddress())) {
            detachedCriteria.add(Restrictions.like("address",
                    customer.getAddress(), MatchMode.ANYWHERE));
        }
        if (sourceList != null && sourceList.size() != 0) {
            detachedCriteria.add(Restrictions.in("source", sourceList));
        }
        if (ownerList != null && ownerList.size() != 0) {
            detachedCriteria.add(Restrictions.in("owner", ownerList));
        } else {
            int flag = 0;
            //Hibernate.initialize(user.getRoleSet());
            for (Role r : user.getRoleSet()) {
                if (r.getValue().equals("admin")
                        || r.getValue().equals("salesManager")) {
                    flag = 1;
                    break;
                }
            }
            if (flag == 1) {
                ownerList = userDao.getList("dept", user.getDept());
                detachedCriteria.add(Restrictions.in("owner", ownerList));
            } else {
                user = userDao.get(user.getId());
                detachedCriteria.add(Restrictions.eq("owner", user));
            }
        }
        if (levelList != null && levelList.size() != 0) {
            detachedCriteria.add(Restrictions.in("level", levelList));
        }
        detachedCriteria.add(Restrictions.eq("status", customer.getStatus()));
        pager = customerDao.findByPager(pager, detachedCriteria);
        return pager;
    }

    @Override
    public Pager<Customer> getByPager(Customer customer, Pager pager,
                                      List<User> ownerList, List<Source> sourceList,
                                      List<Level> levelList, User user) {
        DetachedCriteria detachedCriteria = DetachedCriteria
                .forClass(Customer.class);
        if (StringUtils.isNotBlank(customer.getName())) {
            detachedCriteria.add(Restrictions.like("name", customer.getName(),
                    MatchMode.ANYWHERE));
        }
        if (StringUtils.isNotBlank(customer.getAddress())) {
            detachedCriteria.add(Restrictions.like("address",
                    customer.getAddress()));
        }
        if (sourceList != null && sourceList.size() != 0) {
            detachedCriteria.add(Restrictions.in("source", sourceList));
        }
        if (ownerList != null && ownerList.size() != 0) {
            detachedCriteria.add(Restrictions.in("owner", ownerList));
        } else {
            int flag = 0;
            for (Role r : user.getRoleSet()) {
                if (("admin").equals(r.getValue())
                        || ("salesManager").equals(r.getValue())) {
                    flag = 1;
                    break;
                }
            }
            if (flag == 1) {
                ownerList = userDao.getList("dept", user.getDept());
                detachedCriteria.add(Restrictions.in("owner", ownerList));
            } else {
                user = userDao.get(user.getId());
                detachedCriteria.add(Restrictions.eq("owner", user));
            }
        }
        if (levelList != null && levelList.size() != 0) {
            detachedCriteria.add(Restrictions.in("level", levelList));
        }
        detachedCriteria.add(Restrictions.eq("status", customer.getStatus()));
        // modify by yejf on 2014/1/22 10:35
        // detachedCriteria.add(Restrictions.like("status",customer.getStatus()));
        pager = customerDao.findByPager(pager, detachedCriteria);
        return pager;
    }

    @Override
    public void backSea(Customer customer, String loginUserId) {
        customer = customerDao.get(customer.getId());
        customer.setBackSeaDate(new Date());
        customer.setBackSeaUserId(loginUserId);
        customer.setStatus(Status.SEA);
        customer.setOwner(null);
        customerDao.update(customer);
    }

    @Override
    public Pager<Customer> getAllSeaByPager(Pager pager) {
        DetachedCriteria detachedCriteria = DetachedCriteria
                .forClass(Customer.class);
        detachedCriteria.add(Restrictions.eq("status", Status.SEA));
        pager = customerDao.findByPager(pager, detachedCriteria);
        return pager;
    }

    @Override
    public Pager<Customer> getByPager(Customer customer, Pager pager,
                                      List<Level> levelList, List<Source> sourceList) {
        DetachedCriteria detachedCriteria = DetachedCriteria
                .forClass(Customer.class);
        if (StringUtils.isNotBlank(customer.getName())) {
            detachedCriteria.add(Restrictions.like("name", customer.getName(),
                    MatchMode.ANYWHERE));
        }
        if (StringUtils.isNotBlank(customer.getAddress())) {
            detachedCriteria.add(Restrictions.like("address",
                    customer.getAddress()));
        }
        if (customer.getSource() != null) {
            detachedCriteria
                    .add(Restrictions.eq("source", customer.getSource()));
        }
        if (levelList != null && levelList.size() != 0) {
            detachedCriteria.add(Restrictions.in("level", levelList));
        }
        if (sourceList != null && sourceList.size() != 0) {
            detachedCriteria.add(Restrictions.in("source", sourceList));
        }
        detachedCriteria.add(Restrictions.eq("status", customer.getStatus()));
        // modify by yejf on 2014/1/22 10:39
        // detachedCriteria.add(Restrictions.ilike("status",
        // "%"+customer.getStatus().toString()+"%"));
        pager = customerDao.findByPager(pager, detachedCriteria);
        return pager;
    }

    @Override
    public void deleteIncludeContacts(String id) {
        for (Contact c : contactDao.getByCustomerId(id)) {
            contactDao.delete(c);
        }
        customerDao.delete(id);
    }

    @Override
    public List<Customer> getByProvinceName(String provinceName) {
        return customerDao.getByProvinceName(provinceName);
    }

    @Override
    public Pager<Customer> getByPager(Customer customer, Pager pager,
                                      List<User> ownerList, List<Source> sourceList,
                                      List<Level> levelList, User user, List<Status> statusList, Date fromDate, Date toDate) {
        DetachedCriteria detachedCriteria = DetachedCriteria
                .forClass(Customer.class);
        if (StringUtils.isNotBlank(customer.getName())) {
            detachedCriteria.add(Restrictions.like("name", customer.getName(),
                    MatchMode.ANYWHERE));
        }
        if (StringUtils.isNotBlank(customer.getAddress())) {
            detachedCriteria.add(Restrictions.like("address",
                    customer.getAddress(), MatchMode.ANYWHERE));
        }
        if (sourceList != null && sourceList.size() != 0) {
            detachedCriteria.add(Restrictions.in("source", sourceList));
        }
        if (statusList != null && statusList.size() != 0) {
            detachedCriteria.add(Restrictions.in("status", statusList));
        }
        if (fromDate != null && toDate != null) {
            //为了生成 小时与分钟
            Calendar cal = Calendar.getInstance();
            cal.setTime(toDate);
            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            toDate = cal.getTime();

            detachedCriteria.add(Restrictions.between("createDate", fromDate, toDate));
        }
        if (ownerList != null && ownerList.size() != 0) {
            detachedCriteria.add(Restrictions.in("owner", ownerList));
        } else {
//            int flag = 0;
//            for (Role r : user.getRoleSet()) {
//                if (("admin").equals(r.getValue())
//                        || ("salesManager").equals(r.getValue())) {
//                    flag = 1;
//                    break;
//                }
//            }
//            if (flag == 1) {
//                ownerList = userDao.getList("dept", user.getDept());
//            } else {
                user = userDao.get(user.getId());
                detachedCriteria.add(Restrictions.eq("owner", user));
//            }
        }
        if (levelList != null && levelList.size() != 0) {
            detachedCriteria.add(Restrictions.in("level", levelList));
        }
        //detachedCriteria.add(Restrictions.eq("status",customer.getStatus()));
        pager = customerDao.findByPager(pager, detachedCriteria);
        return pager;
    }

    @Override
    public Pager<Customer> getByPager(Customer customer, Pager pager,
                                      List<Level> levelList, List<Source> sourceList,
                                      List<Status> statusList) {
        DetachedCriteria detachedCriteria = DetachedCriteria
                .forClass(Customer.class);
        if (StringUtils.isNotBlank(customer.getName())) {
            detachedCriteria.add(Restrictions.like("name", customer.getName(),
                    MatchMode.ANYWHERE));
        }
        if (StringUtils.isNotBlank(customer.getAddress())) {
            detachedCriteria.add(Restrictions.like("address", customer.getAddress(),
                    MatchMode.ANYWHERE));
        }
        if (customer.getSource() != null) {
            detachedCriteria
                    .add(Restrictions.eq("source", customer.getSource()));
        }
        if (levelList != null && levelList.size() != 0) {
            detachedCriteria.add(Restrictions.in("level", levelList));
        }
        if (sourceList != null && sourceList.size() != 0) {
            detachedCriteria.add(Restrictions.in("source", sourceList));
        }
        if (statusList != null && statusList.size() != 0) {
            detachedCriteria.add(
                    Restrictions.in("status", statusList));
        }
        //detachedCriteria.add(Restrictions.eq("status", customer.getStatus()));
        pager = customerDao.findByPager(pager, detachedCriteria);
        return pager;
    }

}
